from PySide6.QtCore import Qt
from PySide6.QtWidgets import QLabel
from qfluentwidgets import CheckBox, TransparentTogglePushButton
from ..common.expand_card import KeywordsExpandCard


class KeywordsCard(KeywordsExpandCard):

    def __init__(self, icon, title, parent=None):
        super().__init__(icon, title, parent)
        self.checked_list = []
        self.checkbox_order = []  # 用于维护 CheckBox 的顺序
        self.choiceToggleButton = TransparentTogglePushButton("未选择关键词", self)
        self.choiceToggleButton.setEnabled(False)

        self.addWidget(self.choiceToggleButton)

        self.__initWidget()

    def __initWidget(self):
        self.viewLayout.setSpacing(19)
        self.viewLayout.setContentsMargins(48, 18, 0, 18)

    def addItems(self, items:list):
        # 清空view的所有子控件
        item_list = list(range(self.viewLayout.count()))
        item_list.reverse()
        print('item_list:', item_list)
        for item in item_list:
            self.viewLayout.itemAt(item).widget().deleteLater()
            self._adjustViewSize()
        
        self.choiceToggleButton.setText('未选择关键词')
        self.choiceToggleButton.setEnabled(False)

        if len(items) == 0:
            self.choiceToggleButton.setText('文件有误，请重新选择')
            return
        
        self.checkbox_order = []  # 重置顺序列表
        for item in items:
            checkbox = CheckBox(item)
            checkbox.stateChanged.connect(self.onCheckStateChanged)
            self.viewLayout.addWidget(checkbox)
            self.checkbox_order.append(item)

            checkbox.show()
            self._adjustViewSize()

    def onCheckStateChanged(self, state):
        if state == Qt.CheckState.Checked.value:
            print('checked:', self.sender().text())
            self.checked_list.append(self.sender().text())
            self.checked_list = sorted(self.checked_list, key=lambda x: self.checkbox_order.index(x))  # 按顺序排序
            self.choiceToggleButton.setText(f"选择了{len(self.checked_list)}个关键词")
            self.choiceToggleButton.setEnabled(True)
        else:
            self.checked_list.remove(self.sender().text())
            if len(self.checked_list) == 0:
                self.choiceToggleButton.setText('未选择关键词')
                self.choiceToggleButton.setEnabled(False)
            else:
                self.checked_list = sorted(self.checked_list, key=lambda x: self.checkbox_order.index(x))  # 按顺序排序
                self.choiceToggleButton.setText(f"选择了{len(self.checked_list)}个关键词")
                self.choiceToggleButton.setEnabled(True)

    def setValue(self, value):
        """ set the value of config item """
        pass
    
    def toggleExpand(self):
        """ toggle expand status """
        if not self.isExpand:
            pass
            # self.addItems()
        self.setExpand(not self.isExpand)
   
    def __showInputErrorDialog(self):
        """提示输入的值错误，应填入范围区间内的数字和逗号"""
        pass
